package com.utils;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

//import java.util.stream.Collectors;
public class es_ts {/**
 * 批量添加文档
 *
 * @param lists    文档集合
 * @param indxName 索引名称
 * @return 新增的文档的数量
 * @throws Exception
 */
@Resource(name = "clientByPasswd")
private ElasticsearchClient elasticsearchClient;
public <T> int addDataBatch(List<T> lists, String indxName) throws Exception {
    List<BulkOperation> bulkOperationArrayList =
            lists.stream().map(t -> BulkOperation.of(o -> o.index(i -> i.document(t)))).collect(Collectors.toList());
    //遍历添加到bulk中
    BulkResponse bulkResponse = elasticsearchClient.bulk(b -> b
            .index(indxName)
            .operations(bulkOperationArrayList));
    return bulkResponse.items().size();
}
}
